
from openai import OpenAI
import json
from wxauto import WeChat
import os

import jsonReader
from chatbot.messageList import MessageContent

class WechatResponser:
    def __init__(self, tools, characterName=None):
        # 初始化 FunctionResponser 对象。
        # tools: AI可以调用的方法库
        # 读取 API 凭证
        api_credentials = jsonReader.JsonFileReader('./resource/api-key.json').read_json_file()
        if api_credentials:
            self.client = OpenAI(
                api_key=api_credentials['apiKey'],
                base_url=api_credentials['baseUrl']
            )
        else:
            raise ValueError("API credentials not found or invalid.")

        # 初始化 MessageContent 类
        self.messageList = MessageContent(self.get_character_setting(characterName))
        # 初始化AI设置
        self.model = "GLM-4-Plus"
        self.temprature = 0.9
        self.top_p = 0.7
        self.tools = tools

    def next(self, content):
        # 添加用户消息到消息列表并发送到AI
        self.messageList.addMessage('user', content)
        return self.get_response()
    
    def speak(self):
        return self.messageList.getLastMessage()

    def call_tool(self, tool_calls):
        # 解析tool_calls 并调用工具库获取返回值
        call = tool_calls[0]
        name = call.function.name
        args = json.loads(call.function.arguments)
        result = self.tools.call_tool(name, args)
        self.messageList.addToolReturn(call.id, result)
        return self.get_response()


    def get_response(self):
        # 获取流式响应
        response = self.client.chat.completions.create(
            model=self.model,
            messages=self.messageList.getMessageList(),
            top_p=self.top_p,
            temperature=self.temprature,
            tools=self.tools.toolDescription
        )
    
        if response.choices:
            choice = response.choices[0]
            message = choice.message
            if message.content and message.tool_calls == None:
                # 添加AI消息到消息列表
                self.messageList.addMessage('assistant', message.content)
                return self
            if message.tool_calls:
                return self.call_tool(message.tool_calls)
    
    def get_character_setting(self, characterName):
        if characterName == None:
            characterName = 'characterSetting'
        file_path = os.path.join(os.getcwd(), f'resource/wechat_bot/{characterName}')
        with open(file_path, 'r', encoding='utf-8') as f:
            return f.read()
        
    def add_message(self, content):
        self.messageList.addMessage('assistant', content)